import React, { PureComponent } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Row, Col, Card, List, Avatar, Pagination, Input } from 'antd';
import styles from './MessageManagement.less';

@connect(state => ({
  activities: state.activities,
}))
export default class MessageManagement extends PureComponent {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'activities/fetchList',
    });
  }

  componentWillUnmount() {
  }
  onChange = (pageNumber) => {
    console.log('Page: ', pageNumber);
  }
  handleFormSubmit = (value) => {
    // setTimeout 用于保证获取表单值是在所有表单字段更新完毕的时候
    setTimeout(() => {
      console.log(value);
    }, 0);
  }
  renderActivities() {
    const {
      activities: { list },
    } = this.props;
    return list.map((item) => {
      const events = item.template.split(/@\{([^{}]*)\}/gi).map((key) => {
        if (item[key]) {
          return <a href={item[key].link} key={item[key].name}>{item[key].name}</a>;
        }
        return key;
      });
      return (
        <List.Item key={item.id}>
          <List.Item.Meta
            avatar={<Avatar src={item.user.avatar} />}
            title={
              <span>
                <a className={styles.username}>{item.user.name}</a>
                &nbsp;
                <span className={styles.event}>{events}</span>
              </span>
            }
            description={
              <span className={styles.datetime} title={item.updatedAt}>
                {moment(item.updatedAt).fromNow()}
              </span>
            }
          />
        </List.Item>
      );
    });
  }
  render() {
    const {
      activities: { loading: activitiesLoading },
    } = this.props;
    return (
      <div>
        <Row gutter={24}>
          <Col xl={24} lg={24} md={24} sm={24} xs={24}>
            <Card
              bodyStyle={{ padding: 0 }}
              bordered
              title="动态"
              loading={activitiesLoading}
            >
              <div style={{ textAlign: 'center' }}>
                <Input.Search
                  placeholder="请输入"
                  enterButton="搜索"
                  size="large"
                  onSearch={this.handleFormSubmit.bind(this)}
                  style={{ width: 522, marginTop: 30 }}
                />
              </div>
              <List loading={activitiesLoading} size="large">
                <div className={styles.activitiesList}>
                  {this.renderActivities()}
                </div>
              </List>
              <Pagination showQuickJumper defaultCurrent={2} total={500} onChange={this.onChange} style={{ marginLeft: '40%', marginBottom: 10 }} />
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
}
